import router, { asyncRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = [ '/login', '/404' ] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
	// start progress bar
	NProgress.start()
	// set page title
	document.title = getPageTitle(to.meta.title)
	// determine whether the user has logged in
	const hasToken = getToken()
	console.log(hasToken, 222)
	if (hasToken) {
		if (to.path === '/login') {
			// if is logged in, redirect to the home page
			next({ path: '/' })
			NProgress.done()
		} else {
			const hasGetUserInfo = store.getters.name
			if (hasGetUserInfo) {
				next()
			} else {
				try {
					// get user info
					const { userId, roles: { menus } } = await store.dispatch('user/getInfo')

					// const { userId, roles } = await store.dispatch('user/getInfo')
					// console.log(roles.menus, 6677)
					// console.log(user, 7)
					/* 
          1、这里有用户当前所拥有的动态权限 menus
          2、根据他所拥有的动态权限从所有的动态权限中去匹配获取路由规则对象
          3、addRoutes  添加筛选出来的动态规则对象
          4、仓库获取所有的用户权限  包含动态+静态
          
           */
					const filterRouter = asyncRoutes.filter((item) => {
						// console.log(item, 54)
						const itemName = item.children[0].name //  获取所有的动态路由中的children.name
						const flag = menus.includes(itemName) // 判断name值在不在menus中
						if (flag) {
							return item
						}
					})
					//  4、仓库中合成静态和动态
					filterRouter.push({ path: '*', redirect: '/404', hidden: true })
					store.commit('menu/setMenuList', filterRouter)
					console.log(filterRouter, 888) //  筛选出当前mens对应的动态路由规则对象
					router.addRoutes(filterRouter) //  添加的是用户当前所有的动态权限
					/* 获取用户图像 */
					await store.dispatch('user/getPhoto', userId)
					next({ path: to.path, replace: true })
				} catch (error) {
					// remove token and go to login page to re-login
					await store.dispatch('user/resetToken')
					Message.error(error || 'Has Error')
					next(`/login?redirect=${to.path}`)
					NProgress.done()
				}
			}
		}
	} else {
		/* has no token*/

		// if (whiteList.indexOf(to.path) !== -1) {
		if (whiteList.includes(to.path)) {
			// in the free login whitelist, go directly
			next()
		} else {
			// other pages that do not have permission to access are redirected to the login page.
			next(`/login?redirect=${to.path}`)
			NProgress.done()
		}
	}
})

router.afterEach(() => {
	// finish progress bar
	NProgress.done()
})
